﻿using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using Microsoft.CodeAnalysis.CodeActions;
using Microsoft.CodeAnalysis.CodeFixes;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading.Tasks;
using System.Threading;
using System.Reflection.Metadata;
using Document = Microsoft.CodeAnalysis.Document;

[ExportCodeFixProvider(LanguageNames.CSharp, Name = nameof(MethodTimeCodeFixProvider)), Shared]
public class MethodTimeCodeFixProvider : CodeFixProvider
{
    public sealed override ImmutableArray<string> FixableDiagnosticIds => ImmutableArray.Create(MethodTimeAnalyzer.DiagnosticId);

    public sealed override FixAllProvider GetFixAllProvider()
    {
        return WellKnownFixAllProviders.BatchFixer;
    }

    public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
    {
        var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

        foreach (var diagnostic in context.Diagnostics)
        {
            var diagnosticSpan = diagnostic.Location.SourceSpan;

            // Find the method declaration identified by the diagnostic.
            var declaration = root.FindToken(diagnosticSpan.Start).Parent.AncestorsAndSelf().OfType<MethodDeclarationSyntax>().First();

            // Register a code action that will invoke the fix.
            context.RegisterCodeFix(
                CodeAction.Create("Add [Time] attribute", c => AddTimeAttributeAsync(context.Document, declaration, c), "AddTimeAttribute"),
                diagnostic);
        }
    }

    private async Task<Document> AddTimeAttributeAsync(Document document, MethodDeclarationSyntax methodDeclaration, CancellationToken cancellationToken)
    {
        // Create a new attribute list with the [Time] attribute.
        var timeAttribute = SyntaxFactory.Attribute(SyntaxFactory.IdentifierName("Time"))
                                         .WithLeadingTrivia(methodDeclaration.GetLeadingTrivia());

        var attributeList = SyntaxFactory.AttributeList(SyntaxFactory.SingletonSeparatedList(timeAttribute))
                                         .WithTrailingTrivia(methodDeclaration.GetLeadingTrivia());

        //Insert the attribute list before the method declaration.
        //var newMethodDeclaration = methodDeclaration.WithAttributeLists(
        //    SyntaxFactory.List(new[] { attributeList }).WithTrailingTrivia(methodDeclaration.GetLeadingTrivia()))
        //                                            .WithLeadingTrivia();

        var newMethodDeclaration = methodDeclaration.WithAttributeLists(
    SyntaxFactory.List(new[] { attributeList })
).WithTrailingTrivia(methodDeclaration.GetTrailingTrivia()) // 如果需要 trailing trivia
.WithLeadingTrivia(methodDeclaration.GetLeadingTrivia());

        // Replace the old method declaration with the new one.
        var root = await document.GetSyntaxRootAsync(cancellationToken);
        var newRoot = root.ReplaceNode(methodDeclaration, newMethodDeclaration);

        return document.WithSyntaxRoot(newRoot);
    }
}
